package Top_Interview_Questions.Stack;

import java.util.Stack;

/**
 * @Author: 吕庆龙
 * @Date: 2020/1/8 13:44
 * <p>
 * 功能描述:
 */
public class _0150 {

    /**
     * 执行用时 :8 ms, 在所有 Java 提交中击败了89.48%的用户
     * 内存消耗 :37.4 MB, 在所有 Java 提交中击败了85.69%的用户
     *
     * 执行时间时好时坏,可能是看输入。
     */
    public int evalRPN(String[] tokens) {
        Stack<Integer> numStack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            switch (tokens[i]) {
                case "+":
                    numStack.push(numStack.pop() + numStack.pop());
                    break;
                case "-":
                    numStack.push(-numStack.pop() + numStack.pop());
                    break;
                case "*":
                    numStack.push(numStack.pop() * numStack.pop());
                    break;
                case "/":
                    int num = numStack.pop();
                    numStack.push(numStack.pop() / num);
                    break;
                default:
                    numStack.push(Integer.parseInt(tokens[i]));
            }
        }
        return numStack.pop();
    }

    public int evalRPN1(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String s : tokens) {
            if (s.equals("+")) {
                stack.push(stack.pop() + stack.pop());
            } else if (s.equals("-")) {
                stack.push(-stack.pop() + stack.pop());
            } else if (s.equals("*")) {
                stack.push(stack.pop() * stack.pop());
            } else if (s.equals("/")) {
                int num1 = stack.pop();
                stack.push(stack.pop() / num1);
            } else {
                stack.push(Integer.parseInt(s));
            }
        }
        return stack.pop();
    }
}
